﻿using RRQMCore.ByteManager;
using RRQMSkin.MVVM;
using RRQMSocket;
using RRQMSocket.FileTransfer;
using RRQMSocket.RPC;
using RRQMSocket.RPC.RRQMRPC;
using Server;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Server
{
	class FileServer
	{
        static string IPHost;
        static string VerifyToken;
        public string path = "";
        private static FileService fileService;
        private static RRQMList<SocketClientModel> clientItems;
        public static bool AllowDown { get; set; } = true;
        public static bool AllowUp { get; set; } = true;
        public FileServer(string _IPHost,string _VerifyToken,string _path)
        {
            IPHost = _IPHost;
            VerifyToken = _VerifyToken;
            path = _path;
            clientItems = new RRQMList<SocketClientModel>();
            if (fileService == null)
            {
                fileService = new FileService();
                
                fileService.ClientConnected += FileService_ClientConnected;
                
                fileService.ClientDisconnected += FileService_ClientDisconnected;
                fileService.BeforeFileTransfer += FileService_BeforeFileTransfer;
                fileService.FinishedFileTransfer += FileService_FinishedFileTransfer;
                fileService.Received += FileService_Received;

                RPCService rPCService = new RPCService();
                rPCService.AddRPCParser("fileService", fileService);

                rPCService.RegisterServer<MyOperation>();
            }

            try
            {
                var config = new FileServiceConfig();
                config.ListenIPHosts = new IPHost[] { new IPHost(IPHost) };
                config.ThreadCount = int.Parse("5");
                // config.Logger = new MsgLog(this.ShowMsg);
                config.VerifyToken = VerifyToken;
                config.MaxDownloadSpeed = 1024 * 1024 * 10L;
                config.MaxUploadSpeed = 1024 * 1024 * 10L;
                config.BufferLength = 1024 * 1024;
                config.ClearInterval = 500 * 1000;//500秒后断开
                config.DownloadRoot = _path;
                fileService.Setup(config);
                fileService.Start();
                //   this.Tb_Icon.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#6CE26C"));
                Debug.Success("文件服务器启动成功");
            }
            catch (Exception ex)
            {
                //    this.Tb_Icon.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#E8E8EC"));
                Debug.Error(ex.Message);
            }


            //  CreateFileService();
        }

        void setPath(string path)
        {
            try
            {
                var config = new FileServiceConfig();
                config.DownloadRoot = this.path;
            }
            catch (Exception ex)
            {
                //    this.Tb_Icon.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#E8E8EC"));
                Debug.Error(ex.Message);
            }
        }
        private static void FileService_Received(object sender, short? procotol, ByteBlock byteBlock)
        {
            
            string msg = Encoding.UTF8.GetString(byteBlock.Buffer, 2, (int)byteBlock.Length - 2);
            Debug.Log($"收到：协议=“{procotol}”，信息：{msg}");

            byte[] data = Encoding.UTF8.GetBytes(msg);
            ((FileSocketClient)sender).Send(data);
            ((FileSocketClient)sender).SendAsync(data);
            Debug.Log($"已普通回复");

            ((FileSocketClient)sender).Send(10, data, 0, data.Length);
            ((FileSocketClient)sender).SendAsync(10, data, 0, data.Length);
            Debug.Log($"已通过协议回复");
        }

        private static void FileService_FinishedFileTransfer(object sender, TransferFileMessageArgs e)
        {
            if (e.TransferType == TransferType.Download)
            {
                Debug.Success(string.Format("请求的文件：{0}已成功发送\r\n", e.UrlFileInfo.FileName));
            }
            else
            {
                Debug.Success(string.Format("已收到发来的文件：{0}\r\n", e.UrlFileInfo.FileName));
            }
        }

        private static void FileService_BeforeFileTransfer(object sender, FileOperationEventArgs e)
        {
            if (e.TransferType == TransferType.Upload)
            {
                if (!Directory.Exists("ServiceReceiveDir"))
                {
                    Directory.CreateDirectory("ServiceReceiveDir");
                }
                e.UrlFileInfo.SaveFullPath = @"ServiceReceiveDir\" + e.UrlFileInfo.FileName;

                e.IsPermitOperation = AllowUp;//是否允许接收
            }
            else
            {
                e.IsPermitOperation = AllowDown;//是否允许下载
            }
        }

        private static void FileService_ClientDisconnected(object sender, MesEventArgs e)
        {
            FileSocketClient client = (FileSocketClient)sender;
            int count = clientItems.Count;
            Debug.Log(client.ID + "断开连接");
            /*
            for (int i = 0; i < count; i++)
            {
                if (this.clientItems[i].ID == client.ID)
                {
                    this.clientItems[i].Dispose();
                    UIInvoke(() =>
                    {
                        this.clientItems.RemoveAt(i);
                    });
                    break;
                }
            }*/
        }

        private static void FileService_ClientConnected(object sender, MesEventArgs e)
        {
            FileSocketClient client = (FileSocketClient)sender;
            SocketClientModel socketClientModel = new SocketClientModel(client);
            socketClientModel.Begin();
            clientItems.Add(socketClientModel);
            Debug.Success(client.ID + "已连接");

        }

    }
    public class MyOperation : ServerProvider
    {
        [RRQMRPC]
        public string SayHello(int a)
        {
            return a.ToString();
        }
    }


	
}
